package org.dearsoft.keepleaping.seam.example.dvdstore.accountdeposits;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.dearsoft.keepleaping.seam.example.dvdstore.accountdeposits.Record.Status;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.bpm.ResumeProcess;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jbpm.graph.exe.ProcessInstance;

@Stateful
@Name("showDepositsRecords")
public class ShowRecordAction implements Serializable, ShowRecord {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -801275567882255714L;
	
	@PersistenceContext(type = PersistenceContextType.EXTENDED)
	private EntityManager em;
	
	@In(required=false) 
	private ProcessInstance processInstance;
	
	@DataModel
	private List<Record> depositRecords;
	
	@DataModelSelection @Out(required = false)
	private Record selectedRecord;
	
	
	/* (non-Javadoc)
	 * @see org.dearsoft.keepleaping.seam.example.dvdstore.accountdeposits.ShowRecord#showRecords()
	 */
	@SuppressWarnings("unchecked")
	@Begin @Factory(value = "depositRecords")
	public String showRecords() {
		depositRecords = em.createQuery(
				"select record from Record record where record.customer = #{currentUser} order by record.depositTime DESC")
				.getResultList();
		return "showDepositsRecords";
	}
	
	/**
	 * 为@ResumeProcess method提供processKey。
	 * 
	 * @deprecated 可以直接使用@DataModel property：@ResumeProcess(definition = "...",processKey = "#{depositRecords.rowData.id}")
	 * @return
	 */
	@Deprecated
	@Factory
	public Object getProcessKey() {
		return selectedRecord.getId();
	}
	
	/* (non-Javadoc)
	 * @see org.dearsoft.keepleaping.seam.example.dvdstore.accountdeposits.ShowRecord#cancel()
	 */
	@ResumeProcess(definition = "AccountDeposits",processKey = "#{depositRecords.rowData.id}")
	public String cancel() {
		em.refresh(selectedRecord);
		if (!selectedRecord.getStatus().equals(Status.OPEN)) {
			// 此次充值申请已经是“非打开”状态，无需做任何事。
			// 返回null将取消@ResumeProcess的作用，并重新显示当前视图。
			return null; 
		}
		selectedRecord.setStatus(Status.CANCELLED);
		processInstance.signal("cancel");
		return showRecords(); //重新显示当前视图。
	}
	
	/* (non-Javadoc)
	 * @see org.dearsoft.keepleaping.seam.example.dvdstore.accountdeposits.ShowRecord#remove()
	 */
	@Remove
	public void remove() {		
	}

}
